package net.guoyixian.admin.shiro;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import net.guoyixian.common.redis.RedisKeyPrefixUtils;
import net.guoyixian.common.redis.RedisService;
import net.guoyixian.common.web.ValidationTimeUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.JsonProcessingException;

public class CopyOfRedisSessionDAO extends AbstractSessionDAO {

	private static Logger logger = LoggerFactory
			.getLogger(CopyOfRedisSessionDAO.class);

	@Autowired
	private RedisService redisService;

	@Override
	public void update(Session session) throws UnknownSessionException {
		this.saveSession(session);
	}

	/**
	 * 保存session
	 * 
	 * @param session
	 * @throws UnknownSessionException
	 * @throws JsonProcessingException
	 */
	private void saveSession(Session session) throws UnknownSessionException {
		if (session == null || session.getId() == null) {
			logger.error("session or session id is null");
			return;
		}
		byte[] key = getByteKey(session.getId());
		byte[] value = SerializeUtils.serialize(session);

		session.setTimeout(ValidationTimeUtils.SESSION_TIME * 1000);// 单位是毫秒
		this.redisService.set(key, value,
				(int) ValidationTimeUtils.SESSION_TIME);// 过期时间为秒
	}

	@Override
	public void delete(Session session) {
		// TODO Auto-generated method stub
		if (session == null || session.getId() == null) {
			logger.error("session or session id is null");
			return;
		}
		//1、删除session信息
		redisService.del(this.getByteKey(session.getId()));
		String currentUserName = (String)session.getAttribute("currentUserName");
		if(StringUtils.isNotEmpty(currentUserName)){
			//2、删除role信息
			redisService.del(RedisKeyPrefixUtils.ROLE_ADMIN_PREFIX+currentUserName);
			//3、删除pemission信息
			redisService.del(RedisKeyPrefixUtils.PERMISSION_ADMIN_PREFIX+currentUserName);
		}
	}

	@Override
	public Collection<Session> getActiveSessions() {
		Set<Session> sessions = new HashSet<Session>();

		Set<byte[]> keys = redisService
				.keys((RedisKeyPrefixUtils.SESSION_ADMIN_PREFIX + "*")
						.getBytes());

		if (keys != null && keys.size() > 0) {
			for (byte[] key : keys) {
				Session s = (Session) SerializeUtils.deserialize(redisService
						.get(key));
				sessions.add(s);
			}
		}
		return sessions;
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = this.generateSessionId(session);
		this.assignSessionId(session, sessionId);
		this.saveSession(session);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		if (sessionId == null) {
			logger.error("session id is null");
			return null;
		}
		byte[] sessioninfo = redisService.get(getByteKey(sessionId));
		if (sessioninfo != null && sessioninfo.length > 0) {
			return (Session) SerializeUtils.deserialize(sessioninfo);
		}
		return null;
	}

	/**
	 * 获得byte[]型的key
	 * 
	 * @param key
	 * @return
	 */
	private byte[] getByteKey(Serializable sessionId) {
		String preKey = RedisKeyPrefixUtils.SESSION_ADMIN_PREFIX + sessionId;
		return preKey.getBytes();
	}
}